<template>
  <div class="form_modal">
    <el-dialog
      :visible.sync="modal1"
      center
      :before-close="handleClose">
      <div class="modal_title"> <span> {{title_name}} </span></div>
      <el-form :model="formData" :rules="rules" ref="formData" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="formData.projectName" size="small" placeholder="请输入项目名称" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="项目编码" prop="projectCode">
              <el-input v-model="formData.projectCode" size="small" placeholder="请输入项目编码" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="typeInfo">
              <el-select v-model="formData.typeInfo" placeholder="请选择项目类型" size="small" style="width: 100%;">
                <el-option v-for="(item, index) in projectType" :value="item.itemName" :label="item.itemName" :key="index">
                  {{item.itemName}}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目账号" prop="subAccount">
              <el-input v-model="formData.subAccount" size="small" placeholder="请输入登录账号" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="项目密码" prop="subAccPwd">
              <el-input v-model="formData.subAccPwd" size="small" placeholder="请输入登录密码" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="省份" prop="province">
              <el-select v-model="formData.province" filterable size="small" @change="selectProvinceFun($event)" placeholder="请选择省份" style="width: 200px;">
                <el-option value="" label="请选择省份"></el-option>
                <el-option :value="item.id" :label="item.name" v-for="(item, index) in provinceList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="市" prop="city">
              <el-select v-model="formData.city" filterable size="small" @change="selectCityFun($event)" placeholder="请选择城市" style="width: 180px;">
                <el-option value="" label="请选择城市"></el-option>
                <el-option :value="item.id" :label="item.name" v-for="(item, index) in cityList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="区县" prop="county">
              <el-select v-model="formData.county" filterable size="small" @change="selectAreaFun($event)" placeholder="请选择区县" style="width: 200px;">
                <el-option value="" label="请选择区县"></el-option>
                <el-option :value="item.id" :label="item.name" v-for="(item, index) in areaList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="上传图片" prop="">
          <el-upload
            ref="upload"
            action="#"
            :limit="limit"
            :calss="{ disabled: imgFileList.length === 1}"
            :file-list="imgFileList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-change="OnChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            accept="image/jpeg,image/png"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，最多上传1张且单张图片不超过5M
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt=""/>
          </el-dialog>
        <!-- <el-button type="primary" @click="submitUpload()">确定</el-button> -->
        </el-form-item>
        <el-form-item label="详细地址" prop="projectAddrInfo">
            <el-input type="textarea" v-model="formData.projectAddrInfo" style="width: 800px;"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input type="textarea" v-model="formData.remark" style="width: 800px;"></el-input>
        </el-form-item>
      </el-form>

      <!-- 保存--取消按钮 -->
      <el-row :gutter="24" type="flex" justify="end">
        <el-col :span="4">
          <el-button type="primary" @click="submitForm('formData')">确 定</el-button>
        </el-col>
        <el-col :span="4">
          <el-button @click="handleClose('formData')">取 消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { searchCity, getUserByStatus } from '@/api/userApi'
import { uploadPic } from '@/api/project'
export default {
  props:['historyData'],
  data(){
    return {
      imgFileList: [],
      //图片上传的参数
      visible: false,
      uploadUrl: "",
      limit: 1,
      hideUpload: false, //是否显示上传图片的加号
      deleteImgFileList: [], //存已被删除了的图片的id
      dialogImageUrl: '',
      dialogVisible: false,
      isCustom: this.$store.state.user.roles.includes("custom"),
      title_name: '',
      modal1: false,
      projectType:[
        {itemValue: 1, itemName:"水利"},
        {itemValue: 2, itemName:"文保"},
        {itemValue: 3, itemName:"江堤"},
        {itemValue: 4, itemName:"其他"}
      ],
      users: [],
      provinceList:[], //省
      cityList: [], //市
      areaList: [], //区
      formData: {
        projectName: '',
        projectCode:'',
        typeInfo: '',
        subAccount: '',
        subAccPwd: '',
        projectAddrInfo: '',
        remark: '',
        province: '',
        city: '',
        county: '',
      },
      rules: {
        projectName: [
          { required: true, message: '项目名称不能为空!', trigger: 'blur' },
          { type: 'string', max: 50, message: '不能超过50个字符', trigger: 'blur' },
        ],
        projectCode: [ { required: true, type: 'string', message: '不能为空!', trigger: 'blur' }],
        typeInfo:[
          { required: true, type: 'string', message: '不能为空!', trigger: 'blur' }
        ],
        projectAddrInfo:[
          { required: true, type: 'string', message: '不能为空!', trigger: 'blur' }
        ],
        // userId: [
        //   { required: true, type: 'string', message: '不能为空!', trigger: 'blur' }
        // ],
        remark:[
          { required: false, type: 'string', message: '不能为空!', trigger: 'blur' }
        ],
        province:[
          { required: true, type: 'number', message: '不能为空!', trigger: 'blur' }
        ],
        city:[
          { required: true, type: 'number', message: '不能为空!', trigger: 'blur' }
        ],
        county:[
          { required: true, type: 'number', message: '不能为空!', trigger: 'blur' }
        ]
      },
    }
  },
  methods:{
    //点击上传图片
    submitUpload() {
      let formData = new FormData(); //  用FormData存放上传文件
      this.imgFileList.forEach((file) => {
        // console.log(file.raw, 'size:',file.size);
        formData.append("uploadPic", file.raw);
      });
      this.$axios({
        method: 'post',
        data: formData,
        headers:{'Content-Type':'multipart/form-data'},
        url: '/xiaoyi/oss/ossUploadPhoto.action',
      }).then((res)=>{
        if (res && res.statusCode === '200') {
          this.$message.success('图片上传' + res.statusMsg)
          // 上传其他表格信息
          // this.$refs.upload.clearFiles();
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    //预览图片时
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    OnChange(file, fileList) {
      const isType = file.type === "image/jpeg" || "image/png";
      const isLt100M = file.size / 1024 / 1024 < 1024;

      if (!isType) {
        this.$message.error("上传头像图片只能是 JPG/png 格式!");
        fileList.pop();
      }
      if (!isLt100M) {
        this.$message.error("请检查，上传文件大小不能超过1G!");
        fileList.pop();
      }
      this.imgFileList.push(file);
      this.hideUpload = true
      // this.hideUpload = fileList.length >= this.limit;
    },
    //删除图片时
    handleRemove(file, fileList) {
      if (file.id) {
        console.log("删除了已被上传过的图片:", file.id);
        this.deleteImgFileList.push(file.id);
      }
      this.dataForm.imgFileList = fileList;
      this.hideUpload = fileList.length >= this.limit;
    },
    //文件超出个数限制时
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 省
    selectProvinceFun(provinceId){
      searchCity({ parentId: provinceId ? provinceId : this.formData.province}).then((res)=>{
        if (res.statusCode == 200){
          this.cityList = res.data
        }
      })
    },
    //市
    selectCityFun(cityId){
      searchCity({ parentId: cityId ? cityId : this.formData.city}).then((res)=>{
        if (res.statusCode == 200){
          this.areaList = res.data
        }
      })
    },
    // 区
    selectAreaFun(){

    },
    //提交
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.submitUpload(); //图片上传接口
          let projectTypeId = ''
          this.projectType.map(v => {
            if(v.itemName == this.formData.typeInfo){
              projectTypeId = v.itemValue
            }
          })
          let provinceName = '', cityName = '', countyName = '', userName = '', status = '', statusinfo = "";
          this.provinceList.map(v => {
            if(v.id === this.formData.province){
              provinceName = v.name
            }
          })
          this.cityList.map(v => {
            if(v.id === this.formData.city){
              cityName = v.name
            }
          })
          this.areaList.map(v => {
            if(v.id === this.formData.county){
              countyName = v.name
            }
          })
          this.users.map(v => {
            if(v.id === this.formData.userId){
              userName = v.userName
              status = v.status
              statusinfo = v.statusinfo
            }
          })
          let result = {
            status:  status,
            statusinfo: statusinfo,
            projectTypeId: projectTypeId,
            provinceName: provinceName,
            cityName: cityName,
            countyName: countyName,
            ...this.formData,
            userId: this.$store.state.user.id,
            userName: this.$store.state.user.account
          }

          this.$emit('submit', result)
          this.modal1 = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //查询省市区/县
    searchProvince(){
      // 查询省
      searchCity({ parentId: 0}).then((res)=>{
        // console.log("省：", res.data)
        if (res.statusCode == 200){
          this.provinceList = res.data
        }
      })
      // 查询客户 项目类型
      getUserByStatus(1).then(res => {
        // console.log("项目类型:", res.data)
        if (res.statusCode == 200){
          this.users = res.data
        }
      })
    },
    // 取消
    handleClose(form){
      this.modal1 = false;
      this.formData = {}
      // this.$refs[form].resetFields(); //重置清空
    }
  },
  watch:{
    historyData: function (val) {
      // console.log("this.historyData:",this.historyData);
      this.formData = val
    },
    title_name: function (title) {
      if (title === '添加项目'){
        this.formData = {}
      } else if ( title === '编辑项目'){
        console.log('formData:', this.formData)

        // 回调省的接口
        this.selectProvinceFun(this.formData.province)

        // 回调 市接口
        this.selectCityFun(this.formData.city)
      }
    }
  }
}
</script>

<style scoped>
  /deep/.disabled .el-upload--picture-card {
    display: none;
  }
  /* @import url('../../assets/css/dialog.css'); */
</style>
